package com.example.servlet.auth;

import com.example.entity.Order;
import com.example.entity.Passenger;
import com.example.entity.Ticket;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.BCryptUtil;
import com.example.utils.MybatisUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

@WebServlet("/user_unsubscribe")
public class UnsubscribeServlet extends HttpServlet {
    private UserService service;
    private SqlSession sqlSession;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new UserServiceImpl(sqlSession);
    }

    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        String u_password  = req.getParameter("current_password");
        String del_account = req.getParameter("del_account");
        // 从数据库中获取存储的哈希密码
        String storedHashedPassword = service.getHashedPasswordByAccount(del_account);
        if (storedHashedPassword != null) {
            // 使用 BCryptUtil 验证密码
            boolean isPasswordCorrect = BCryptUtil.verifyPassword(u_password, storedHashedPassword);
            if (isPasswordCorrect) {
                try{
                    //删订单
                    List<Order> orders = service.getOrderListByUserId(user.getU_id());
                    for(Order order:orders){
                        List<Ticket> tickets = service.getTicketListByOrderId(order.getId());
                        if(Objects.equals(order.getStatusText(), "待支付")){
                            for(Ticket ticket : tickets){
                                if(Objects.equals(ticket.getSeat_type(), "经济舱")){
                                    if(service.addEconomySpace(ticket.getFlightNo())==0){
                                        throw new Exception("Failed to add economy space");
                                    }
                                } else if (Objects.equals(ticket.getSeat_type(), "商务舱")) {
                                    if(service.addBusinessSpace(ticket.getFlightNo())==0){
                                       throw new Exception("Failed to add business space");
                                    }
                                }else{
                                    if(service.addFirstSpace(ticket.getFlightNo())==0){
                                        throw new Exception("Failed to add first space");
                                    }
                                }
                                if(service.deleteTicket(ticket.getId())==0){
                                    throw new Exception("Failed to delete ticket");
                                }
                            }
                        } else if (Objects.equals(order.getStatusText(), "已支付") || Objects.equals(order.getStatusText(), "退款中")) {
                            for(Ticket ticket : tickets){
                                if(Objects.equals(ticket.getSeat_type(), "经济舱")){
                                    if(service.addEconomySpace(ticket.getFlightNo())==0){
                                        throw new Exception("Failed to add economy space");
                                    }
                                } else if (Objects.equals(ticket.getSeat_type(), "商务舱")) {
                                    if(service.addBusinessSpace(ticket.getFlightNo())==0){
                                        throw new Exception("Failed to add business space");
                                    }
                                }else{
                                    if(service.addFirstSpace(ticket.getFlightNo())==0){
                                        throw new Exception("Failed to add first space");
                                    }
                                }
                                if(service.deleteTicket(ticket.getId())==0){
                                    throw new Exception("Failed to delete ticket");
                                }
                                if(service.addBankMoneyByUserIDtypeAndIDcard(user.getID_type(), user.getID_card(), order.getPrice())==0){
                                    throw new Exception("Failed to update bank money");
                                }
                            }
                        }else{
                            for(Ticket ticket : tickets){
                                if(service.deleteTicket(ticket.getId())==0){
                                    throw new Exception("Failed to delete ticket");
                                }
                            }
                        }
                    }
                    if(service.getOrderNumByUserId(user.getU_id())!=0){
                        if(service.deleteOrder(user.getU_id())==0){
                            System.out.println(0);
                            throw new Exception("Failed to delete order");
                        }
                    }
                    //删机票
                    Passenger passenger = service.getPassengerByIDtypeAndIDcard(user.getID_type(), user.getID_card());
                    List<Ticket> tickets = service.getTicketListByPassengerId(passenger.getPassenger_id());
                    for(Ticket ticket : tickets){
                        Order order = service.getOrderById(ticket.getOrder_id());
                        User orderUser = service.getUserById(order.getUserId());
                        if(Objects.equals(ticket.getStatusText(), "即将起飞") || Objects.equals(ticket.getStatusText(), "计划中") || Objects.equals(ticket.getStatusText(), "待退款")){
                            if(Objects.equals(ticket.getSeat_type(), "经济舱")) {
                                if(service.addEconomySpace(ticket.getFlightNo())==0){
                                    throw new Exception("Failed to add economy space");
                                }
                            }
                            else if (Objects.equals(ticket.getSeat_type(), "商务舱")) {
                                if(service.addBusinessSpace(ticket.getFlightNo())==0){
                                    throw new Exception("Failed to add business space");
                                }
                            }
                            else {
                                if(service.addFirstSpace(ticket.getFlightNo())==0){
                                    throw new Exception("Failed to add first space");
                                }
                            }
                            if(service.addBankMoneyByUserIDtypeAndIDcard(orderUser.getID_type(),  orderUser.getID_card(), ticket.getPrice())==0){
                                throw new Exception("Failed to update bank money");
                            }
                            if(order.getPassengers() == 1){
                                if(service.deleteOrder(order.getId())==0){
                                    System.out.println(1);
                                    throw new Exception("Failed to delete order");
                                }
                            }else{
                                if(service.updateOrderPriceAndPassengerNum(order.getId(), ticket.getPrice())==0){
                                    throw new Exception("Failed to update order price and passenger num");
                                }
                            }
                        }else if(Objects.equals(ticket.getStatusText(), "待支付")){
                            if(Objects.equals(ticket.getSeat_type(), "经济舱")) {
                                if(service.addEconomySpace(ticket.getFlightNo())==0){
                                    throw new Exception("Failed to add economy space");
                                }
                            }
                            else if (Objects.equals(ticket.getSeat_type(), "商务舱")) {
                                if(service.addBusinessSpace(ticket.getFlightNo())==0){
                                    throw new Exception("Failed to add business space");
                                }
                            }
                            else {
                                if(service.addFirstSpace(ticket.getFlightNo())==0){
                                    throw new Exception("Failed to add first space");
                                }
                            }
                            if(order.getPassengers() == 1){
                                if(service.deleteOrder(order.getId())==0){
                                    System.out.println(2);
                                    throw new Exception("Failed to delete order");
                                }
                            }else{
                                if(service.updateOrderPriceAndPassengerNum(order.getId(), ticket.getPrice())==0){
                                    throw new Exception("Failed to update order price and passenger num");
                                }
                            }
                        }else{
                            if(order.getPassengers() == 1){
                                if(service.deleteOrderById(order.getId())==0){
                                    System.out.println(3);
                                    throw new Exception("Failed to delete order");
                                }
                            }else{
                                if(service.updateOrderPriceAndPassengerNum(order.getId(), ticket.getPrice())==0){
                                    throw new Exception("Failed to update order price and passenger num");
                                }
                            }
                        }
                        if(service.deleteTicket(ticket.getId())==0){
                            throw new Exception("Failed to delete ticket");
                        }
                    }
                    //删乘客
                    if(service.deletePassenger(passenger.getPassenger_id())==0){
                        throw new Exception("Failed to delete passenger");
                    }
                    //删用户
                    if(service.deleteUser(user.getU_id())==0){
                        throw new Exception("Failed to delete user");
                    }
                    service.commit();
                    resp.sendRedirect("host");
                } catch (Exception e) {
                    e.printStackTrace();
                    service.rollback();
                    req.getSession().setAttribute("unsubscribe_failure", new Object());
                    resp.sendRedirect("user_account_manage");
                }
            }
            else{
                req.getSession().setAttribute("password_error", new Object());
                resp.sendRedirect("user_account_manage");
            }
        }
    }
}